<?php
/**
 * 后台角色控制器
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types=1);

namespace app\admin\controller;

use support\Request;
use support\Response;
use app\admin\model\AdminMenu;
use app\admin\model\AdminRole;
use app\admin\validate\AdminRoleValidate;
use app\admin\traits\{AdminIndexTrait,AdminAddTrait,
    AdminEditTrait, AdminDelTrait,AdminEnableTrait,
    AdminDisableTrait};

class AdminRoleController extends AdminBaseController
{
    use AdminIndexTrait;
    use AdminAddTrait;
    use AdminEditTrait;
    use AdminDelTrait;
    use AdminEnableTrait;
    use AdminDisableTrait;

    public function __construct()
    {
        $this->model = new AdminRole();
        $this->validate = new AdminRoleValidate();
        parent::__construct();
    }


    /**
     * 授权
     * @param Request $request
     * @param AdminRole $model
     * @return Response
     */
    public function access(Request $request, AdminRole $model): Response
    {
        $id = $request->input('id');
        $data = $model->findOrEmpty($id);
        if ($request->method()==='POST') {
            $param = $request->all();
            if (!isset($param['url'])) {
                return admin_error('请至少选择一项权限');
            }
            $param['url'] = array_map('intval', $param['url']);
            if (!in_array(1, $param['url'], true) || !in_array(2, $param['url'], true) || !in_array(18, $param['url'], true)) {
                return admin_error('首页和个人资料权限必选');
            }

            asort( $param['url']);

            if (false !== $data->save($param)) {
                return admin_success('操作成功',[],URL_BACK);
            }
            return admin_error();
        }

        $menu = (new AdminMenu)->order('sort_number', 'asc')
            ->order('id', 'asc')
            ->column('*', 'id');
        $html = $this->authorizeHtml($menu, $data->url);

        $this->assign([
            'data' => $data,
            'html' => $html,
        ]);

        return $this->fetch();
    }
}
